import {baseUrl} from './env'
import errorLog from './errorLog'
import {localStorage} from '../common/util'

const csrfConfig = {
    'Accept':'application/json'
};

export default (url = '', data = {}, type = 'GET') => {
    try {
        data.token = localStorage.getStore('loginToken');
        return new Promise((resolve, reject) => {
            uni.request({
                url: baseUrl + url,
                data: data,
                header: csrfConfig,
                method: type.toUpperCase(),
                success: (requestObj) => {
                    if (requestObj.statusCode == 200) {
                        let obj = requestObj.data
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        if(obj.status==1){
                            if(obj.result!=null && typeof obj.result.token !== "undefined"){
                                localStorage.setStore('loginToken',obj.result.token);
                            }
                            resolve(obj);
                        }else{
                            errorLog({type:"status",data:obj}).then((res)=>{
                                reject(res);
                            });
                        }
                    } else {
                        errorLog({type:"statusCode",data:requestObj}).then((res)=>{
                            reject(res);
                        });
                    }
                },
                fail: (error) => {
                    errorLog({type:"error",data:error}).then((res)=>{
                        reject(res);
                    });
                }
            });
        });
    } catch (error) {
        throw new Error(error)
    }
}